package com.cloudtasks;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;

import com.cloudtasks.shared.CloudTasksRequestFactory;
import com.cloudtasks.shared.ItemProxy;
import com.cloudtasks.shared.ListProxy;
import com.cloudtasks.shared.TaskProxy;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class AsyncFetchItem extends AsyncTask<Long, Void, List<ItemProxy>> {

    private final UsersDisplayActivity activity;
    private boolean newTask = false;

    public AsyncFetchItem(UsersDisplayActivity usersDisplayActivity) {
        super();
        this.activity = usersDisplayActivity;
    }

    @Override
    protected List<ItemProxy> doInBackground(Long... arguments) {
        final List<ItemProxy> list = new ArrayList<ItemProxy>();

        // INSERT RPC HERE!
        CloudTasksRequestFactory factory = Util.getRequestFactory(activity,
        		CloudTasksRequestFactory.class);
        
        if (arguments.length == 0 || arguments[0] == -1) 
        {
	        System.out.println("I'm here");
	        //Fetch Users
	       
        	factory.taskRequest().queryAllItems().fire(new Receiver<List<ItemProxy>>() {
				@Override
				public void onSuccess(List<ItemProxy> arg0) {
					list.addAll(arg0);
					
				}
	        });
        } 
        else if(arguments[0]==100) {
        	newTask = true;
        	//Reading in new user for some reason
        	factory.taskRequest().readTask(arguments[0]).fire(new Receiver<TaskProxy>() {

				@Override
				public void onSuccess(TaskProxy arg0) {
					//list.add(arg0);
				}
			});
        }
        
        

        return list;
    }

    @Override
    protected void onPostExecute(List<ItemProxy> result) {
    	if (newTask) {
    		//activity.compare_users(result);
    	} else {
    		//while(activity.sync_var!=2){};
    		activity.compare_items(result);
    	}
    }
}
